# -*- coding:utf-8 -*-
import os
import sys
import shutil
import datetime
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *


class PackZip(QWidget):

    def __init__(self):
        super(PackZip, self).__init__()

        self.btn_style = """QPushButton{color:black}
                                    QPushButton:hover{color:red}
                                   QPushButton{background-color:#DCDCDC}
                                    QPushButton{border:2px}
                                    QPushButton{border-radius:3px}
                                    QPushButton{padding:3px 3px}"""




        self.mid_font = QFont('', 12, 64)

        self.setWindowTitle('插件打包')
        self.main_layout = QVBoxLayout()
        self.main_layout.setSpacing(20)
        self.show_title = QLabel("打包ZIP")
        self.show_title.setFont(self.mid_font)
        self.show_title.setAlignment(Qt.AlignCenter)
        self.dir_layout = QHBoxLayout()
        self.dir_label = QLabel('插件目录:')
        self.dir_edit = QLineEdit()
        self.dir_btn = QPushButton('选择')
        self.dir_btn.clicked.connect(self._select_script_dir)
        self.dir_btn.setStyleSheet(self.btn_style)
        self.dir_layout.addWidget(self.dir_label)
        self.dir_layout.addWidget(self.dir_edit)
        self.dir_layout.addWidget(self.dir_btn)

        self.out_layout = QHBoxLayout()
        self.out_label = QLabel('输出目录:')
        self.out_eidt = QLineEdit()
        self.out_btn = QPushButton('选择')
        self.out_btn.clicked.connect(self._select_out_dir)
        self.out_btn.setStyleSheet(self.btn_style)
        self.out_layout.addWidget(self.out_label)
        self.out_layout.addWidget(self.out_eidt)
        self.out_layout.addWidget(self.out_btn)

        # self.config_frame = QFrame()
        self.config_layout = QVBoxLayout()
        # self.config_frame.setLayout(self.config_layout)
        self.enable_version_layout = QHBoxLayout()
        self.enable_version_label = QLabel('是否生成版本信息:')
        self.enable_check = QCheckBox('开启')
        self.enable_check.setCheckState(Qt.Checked)
        self.enable_check.clicked.connect(self._enable_version)
        self.enable_version_layout.addWidget(self.enable_version_label)
        self.enable_version_layout.addWidget(self.enable_check)

        self.version_frame = QFrame()
        self.version_layout = QVBoxLayout()
        self.version_frame.setLayout(self.version_layout)
        self.version_name_layout = QHBoxLayout()
        self.version_name_label = QLabel('版本名称:')
        self.create_bytime_checkbox = QCheckBox('按日期生成')
        self.create_bytime_checkbox.setCheckState(Qt.Checked)
        self.create_bytime_checkbox.clicked.connect(self._custom_name)
        self.custom_version_eidt = QLineEdit()
        self.custom_version_eidt.setPlaceholderText('自定义版本名称')
        self.custom_version_eidt.setEnabled(False)
        self.version_name_layout.addWidget(self.version_name_label)
        self.version_name_layout.addWidget(self.create_bytime_checkbox)
        self.version_name_layout.addWidget(self.custom_version_eidt)
        self.mid_name_layout = QHBoxLayout()
        self.mid_name_layout.setAlignment(Qt.AlignLeft)
        self.mid_name_layout.setContentsMargins(0,0,180,0)
        self.mid_name_label = QLabel('中号:')
        self.mid_name_edit = QLineEdit()
        self.mid_name_edit.setFixedWidth(50)
        self.mid_name_layout.addWidget(self.mid_name_label)
        self.mid_name_layout.addWidget(self.mid_name_edit)
        self.last_name_layout = QHBoxLayout()
        self.last_name_layout.setContentsMargins(0,0,180,0)
        self.last_name_label = QLabel('尾号:')
        self.last_name_eidt = QLineEdit()
        self.last_name_eidt.setFixedWidth(50)
        self.last_name_layout.addWidget(self.last_name_label)
        self.last_name_layout.addWidget(self.last_name_eidt)

        self.version_content = QTextEdit()
        self.version_layout.addLayout(self.version_name_layout)
        self.version_layout.addLayout(self.mid_name_layout)
        self.version_layout.addLayout(self.last_name_layout)
        self.version_layout.addWidget(self.version_content)

        self.config_layout.addLayout(self.enable_version_layout)
        self.config_layout.addWidget(self.version_frame)

        self.create_btn = QPushButton('生成')
        self.create_btn.clicked.connect(self._create)
        self.create_btn.setStyleSheet(self.btn_style)

        self.main_layout.addWidget(self.show_title)
        self.main_layout.addLayout(self.dir_layout)
        self.main_layout.addLayout(self.out_layout)
        self.main_layout.addLayout(self.config_layout)
        self.main_layout.addWidget(self.create_btn)

        self.setLayout(self.main_layout)

    def _select_script_dir(self):
        script_dir = QFileDialog.getExistingDirectory(self,'选择文件夹')
        print(script_dir)
        if script_dir:
            self.dir_edit.setText(script_dir)

    def _select_out_dir(self):
        script_dir = QFileDialog.getExistingDirectory(self,'选择文件夹')
        print(script_dir)
        if script_dir:
            self.out_eidt.setText(script_dir)


    def _enable_version(self,status):
        if not status:
            # self.version_name_layout.setEnabled(False)
            self.version_frame.setEnabled(False)
            # self.config_layout.
        else:
            self.version_frame.setEnabled(True)
        print(status)

    def _custom_name(self,status):
        if status:
            self.custom_version_eidt.setEnabled(False)
        else:
            self.custom_version_eidt.setEnabled(True)
        print(status)

    def _create(self):
        version = ''
        script_dir = self.dir_edit.text()
        out_dir = self.out_eidt.text()
        content = self.version_content.toPlainText()
        if script_dir and out_dir and content:
            plugin_name = os.path.split(script_dir)[-1]
            if self.enable_check.isChecked():   #当开启版本信息生成时
                if not self.create_bytime_checkbox.isChecked():  #当使用自定义版本名称时
                    custom_name = self.custom_version_eidt.text()
                    if not custom_name:
                        QMessageBox.information(None,"错误","自定义名称为空")
                    else:
                        mid_name = self.mid_name_edit.text()
                        last_name = self.last_name_eidt.text()
                        if mid_name and last_name:
                            version = custom_name + '.' + mid_name + '.' + last_name
                else:   #当使用默认日期生成时
                    today = datetime.datetime.strftime(datetime.datetime.today(), "%Y%m%d")
                    mid_name = self.mid_name_edit.text()
                    last_name = self.last_name_eidt.text()
                    if mid_name and last_name:
                        version = today+'.'+mid_name+'.'+last_name
                    else:
                        QMessageBox.information(None, "错误", "版本号不完整")

        else:
            QMessageBox.information(None, "错误", "信息不完整")

        # print(version)

        data = {}
        data['plugin_name'] = plugin_name
        data['version'] = version
        data['version_data'] = content


        print(data)
        if version:
            try:
                version_dir = os.path.join(out_dir,version)
                os.makedirs(version_dir,exist_ok=True)
                self._zip(script_dir,version_dir,data)
                self._create_version(version_dir,data)
                QMessageBox.information(None,"提示","完成")
                os.startfile(version_dir)
            except Exception as ERR:
                print('ERR:',str(ERR))
                QMessageBox.information(None, "失败", str(ERR))

    def _zip(self,src_dir,tar_dir,data):
        """
        打包zip
        :param src_dir:
        :param tar_dir:
        :param data:
        :return:
        """
        tar_zip_path = os.path.join(tar_dir,data['plugin_name'])
        zip_path = shutil.make_archive(tar_zip_path, 'zip', root_dir=src_dir)

    def _create_version(self,tar_dir,data):
        """
        创建version.txt
        :param tar_dir:
        :param data:
        :return:
        """
        version_path = os.path.join(tar_dir,'version.txt')
        with open(version_path,'w',encoding='utf8') as w:
            w.write(str(data))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    p = PackZip()
    p.show()
    sys.exit(app.exec_())










